package interceptor;

import cn.hutool.core.util.StrUtil;
import context.BaseContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoInterceptor implements HandlerInterceptor {
    /**
     * 请求前执行——获取用户信息并存放到ThreadLocal
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userInfo = request.getHeader("user-info");

        //判断是否获取到，如果有再存入ThreadLocal
        if (StrUtil.isNotBlank(userInfo)) {
            BaseContext.setCurrentId(Long.valueOf(userInfo));
        }

        //放行，登录校验的逻辑在网关已经做过了
        return true;

    }

    /**
     * 请求后执行——清除ThreadLocal
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
